<template>
  <div class="page-container">
    <div class="in-container">
      <el-row :gutter="8">
        <el-col :span="10">
          <AppTitleBox class="app-title-box" title="字典管理">
            <template #button>
              <el-button @click="addDict()" link type="primary">添加</el-button>
            </template>
            <AppSearchForm @submit="search()" @reset="reset()">
              <el-form-item>
                <el-input
                  v-model="state.query.name"
                  clearable
                  placeholder="输入字典名称或者描述搜索"
                  style="width: 200px"
                />
              </el-form-item>
            </AppSearchForm>
            <AppPageTable
              stripe
              ref="description"
              :data="state.dictTableData.data"
              :singleHighLight="true"
              :autostyle="'height: calc(100% - 32px);'"
              :option="state.dictTableData.option"
              @change="getList()"
              @singleClick="(data) => singleClickGetDetail(data)"
            >
              <el-table-column
                :show-overflow-tooltip="true"
                prop="name"
                label="名称"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="description"
                label="描述"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="dictShare"
                label="字典共享"
              >
                <template #default="scope">
                  {{ scope.row.dictShare == "1" ? "共享" : "未共享" }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="90px" fixed="right">
                <template #default="scope">
                  <el-button
                    @click.stop="updateDict(scope.row)"
                    link
                    type="primary"
                    >编辑</el-button
                  >
                  <el-popconfirm
                    title="确定删除本条数据吗？"
                    @confirm="deleteDict(scope.row)"
                  >
                    <template #reference>
                      <el-button link type="danger">删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </AppPageTable>
          </AppTitleBox>
        </el-col>
        <el-col :span="14">
          <AppTitleBox class="app-title-box" title="字典详情">
            <template #button>
              <el-button
                @click="addDictDetail()"
                link
                v-show="state.dictDetailTableData.dictName"
                type="primary"
                >添加</el-button
              >
            </template>
            <div
              v-show="state.dictDetailTableData.dictName"
              style="height: 100%"
            >
              <AppPageTable
                stripe
                :data="state.dictDetailTableData.data"
                @change="getDetail()"
                :autostyle="'height: 100%;'"
                :option="state.dictDetailTableData.option"
              >
                <el-table-column prop="belong" label="所属字典" />
                <el-table-column prop="label" label="字典标签" />
                <el-table-column prop="value" label="字典值" />
                <el-table-column prop="dictSort" label="排序" />
                <el-table-column label="操作" width="90px" fixed="right">
                  <template #default="scope">
                    <el-button
                      @click="updateDictDetail(scope.row)"
                      link
                      type="primary"
                      >编辑</el-button
                    >
                    <el-popconfirm
                      title="确定删除本条数据吗？"
                      @confirm="deleteDictDetail(scope.row)"
                    >
                      <template #reference>
                        <el-button link type="danger">删除</el-button>
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </AppPageTable>
            </div>
            <div v-show="!state.dictDetailTableData.dictName">
              点击字典查看详情
            </div>
          </AppTitleBox>
        </el-col>
      </el-row>
    </div>
  </div>
  <el-dialog
    width="500px"
    v-model="state.dictdialogData.show"
    :title="state.dictdialogData.title"
  >
    <el-form
      :model="state.dictData"
      :rules="state.dictRules"
      label-width="80px"
      ref="dictForm"
    >
      <el-form-item prop="name" label="名称">
        <el-input v-model="state.dictData.name"></el-input>
      </el-form-item>
      <el-form-item prop="sort" label="描述">
        <el-input
          v-model="state.dictData.description"
          type="textarea"
        ></el-input>
      </el-form-item>
      <el-form-item prop="share" label="字典共享">
        <!-- <el-input v-model="dictData.dict_share" type="textarea"></el-input> -->
        <el-radio-group v-model="state.dictData.dictShare">
          <el-radio :label="1">共享</el-radio>
          <el-radio :label="0">未共享</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDict" link>取消</el-button>
        <el-button type="primary" @click="submitDict"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
    width="500px"
    v-model="state.dictDetailDialogData.show"
    :title="state.dictDetailDialogData.title"
    @close="dictDetailDialogClose"
  >
    <el-form
      :model="state.dictDetailData"
      :rules="state.dictDetailRules"
      label-width="80px"
      ref="dictDetailForm"
    >
      <el-form-item prop="label" label="字典标签">
        <el-input v-model="state.dictDetailData.label"></el-input>
      </el-form-item>
      <el-form-item prop="value" label="字典值">
        <el-input v-model="state.dictDetailData.value"></el-input>
      </el-form-item>
      <el-form-item prop="dictSort" label="排序">
        <el-input-number
          v-model="state.dictDetailData.dictSort"
          :min="1"
          :max="999"
          controls-position="right"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDictDetail" link>取消</el-button>
        <el-button type="primary" @click="submitDictDetail"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, watch, nextTick } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import AppTitleBox from "@/components/AppTitleBox.vue";
import { arrayLastIndexOf } from "xe-utils";
import { ElMessage } from "element-plus";
import request from "@/public/request";
import { useRoute } from "vue-router";

const Route = useRoute();

const state = reactive({
  query: {
    name: "",
  },
  dictTableData: {
    data: [],
    option: useTableOption(),
  },
  dictdialogData: {
    show: false,
    title: "",
  },
  dictData: {
    name: "",
    description: "",
  },
  dictRules: {
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  },
  //详情表格数据
  dictDetailTableData: {
    id: "",
    dictName: "",
    data: [],
    option: useTableOption(),
  },
  //详情表单数据
  dictDetailData: {
    label: "",
    value: "",
    dictSort: 999,
  },
  //详情表单规则
  dictDetailRules: {
    label: [{ required: true, message: "请输入字典标签", trigger: "blur" }],
    value: [{ required: true, message: "请输入字典值", trigger: "blur" }],
    dictSort: [{ required: true, message: "请输入排序值", trigger: "blur" }],
  },
  //详情弹窗数据
  dictDetailDialogData: {
    show: false,
    title: "新增字典详情",
  },
});

const search = () => {
  state.dictTableData.option.page = 1;
  getList();
};
const reset = () => {
  state.query = {
    name: "",
    date: [],
    enabled: "",
  };
  state.dictTableData.option.page = 1;
  getList();
};
const addDict = () => {
  state.dictData = {
    name: "",
    description: "",
    dictShare: 0,
  };
  state.dictdialogData.title = "添加字典";
  state.dictdialogData.show = true;
};
const getList = () => {
  state.dictTableData.option.loading = true;
  request
    .get("/api/basedict/querypage", {
      PageIndex: state.dictTableData.option.page,
      PageSize: state.dictTableData.option.pageSize,
      keyWords: state.query.name,
    })
    .then((res) => {
      state.dictTableData.data = res.content;
      state.dictTableData.option.total = res.totalElements;
    })
    .catch((err) => {
      ElMessage.error("表格数据请求失败");
    })
    .finally(() => {
      state.dictTableData.option.loading = false;
    });
};
const updateDict = (data) => {
  state.dictdialogData.title = "编辑字典";
  state.dictData = JSON.parse(JSON.stringify(data));
  state.dictData.dictShare = parseInt(state.dictData.dictShare);
  state.dictdialogData.show = true;
};
const deleteDict = (data) => {
  if (state.dictDetailTableData.id && state.dictDetailTableData.id == data.id) {
    state.dictDetailTableData = {
      id: "",
      dictName: "",
      data: [],
      option: useTableOption(),
    };
  }
  request.post("/api/basedict/delete", { idArray: [data.id] }).then((res) => {
    if (res == 1) {
      ElMessage.success("成功");
      getList();
    } else if(res == -1) {
      ElMessage.error("有所属数据，无法删除");
    }
  });
};
const cancelDict = () => {
  state.dictdialogData.show = false;
};
const submitDict = () => {
  let url = "";
  if (state.dictData.id) {
    url = "/api/basedict/update";
  } else {
    url = "/api/basedict/create";
  }

  request.post(url, state.dictData).then((res) => {
    if (res.status) {
      ElMessage.success(res.message);
      getList();
      cancelDict();
    } else {
      ElMessage.error(res.message);
    }
  });
  state.dictdialogData.show = false;
};
const singleClickGetDetail = (data) => {
  state.dictDetailTableData.id = data.id;
  state.dictDetailTableData.dictName = data.name;
  getDetail();
};
const getDetail = () => {
  state.dictDetailTableData.option.loading = true;
  request
    .get("/api/basedictdetail/querypage", {
      PageIndex: state.dictDetailTableData.option.page,
      PageSize: state.dictDetailTableData.option.pageSize,
      DictId: state.dictDetailTableData.id,
    })
    .then((res) => {
      res.content = res.content.map((item) => {
        item.belong = state.dictDetailTableData.dictName;
        return item;
      });
      state.dictDetailTableData.data = res.content;
      state.dictDetailTableData.option.total = res.totalElements;
    })
    .finally(() => {
      state.dictDetailTableData.option.loading = false;
    });
};
const addDictDetail = () => {
  state.dictDetailDialogData.title = "新增字典详情";
  state.dictDetailDialogData.show = true;
};
const updateDictDetail = (data) => {
  state.dictDetailData = JSON.parse(JSON.stringify(data));
  state.dictDetailDialogData.title = "编辑字典详情";
  state.dictDetailDialogData.show = true;
};
const deleteDictDetail = (data) => {
  request.post("/api/basedictdetail/delete", { idArray: [data.id] }).then((res) => {
    if (res.status) {
      ElMessage.success(res.message);
      getDetail();
    } else {
      ElMessage.error(res.message);
    }
  });
};
const cancelDictDetail = () => {
  state.dictDetailDialogData.show = false;
};
const submitDictDetail = () => {
  let url = "";
  if (state.dictDetailData.id) {
    url = "/api/basedictdetail/update";
  } else {
    url = "/api/basedictdetail/create";
    state.dictDetailData.dictId = state.dictDetailTableData.id
  }

  request.post(url, state.dictDetailData).then((res) => {
    if (res.status) {
      ElMessage.success(res.message);
      getDetail();
      cancelDictDetail();
    } else {
      ElMessage.error(res.message);
    }
  });
  state.dictDetailDialogData.show = false;
};
const dictForm = ref();
const dictDetailForm = ref();

const dictDetailDialogClose = () => {
  
}

watch(() => state.dictdialogData.show, (newVal) => {
  if (!newVal) {
    nextTick(() => {
      state.dictData = {
        name: "",
        description: "",
        dictShare: 0,
      };
      dictForm.value.resetFields();
    });
  }
});

watch(() => state.dictDetailDialogData.show, (newVal) => {
  if (!newVal) {
    nextTick(() => {
      state.dictDetailData = {
        label: "",
        value: "",
        dictSort: 999,
      };
      dictDetailForm.value.resetFields();
    });
  }
});

const description = ref();

onMounted(async () => {
  getList();

  const { title } = Route.query;

  // console.log('this.option',this.dictTableData.option);

  let res = await request.get("/api/dict/query", {
    PageIndex: state.dictTableData.option.page,
    PageSize: 999,
    keyWords: state.query.name,
  });
  res.content = res.content.map((item) => {
    item.belong = state.dictDetailTableData.dictName;
    return item;
  });
  state.dictDetailTableData.data = res.content;

  let obj = state.dictDetailTableData.data.filter(
    (item) => item.description == title
  )[0];
  let index = state.dictDetailTableData.data.indexOf(obj);

  if (
    title == "结算类型" ||
    title == "企业类型" ||
    title == "货物来源" ||
    title == "运输条款" ||
    title == "付款方式"
  ) {
    // console.log(this.dictDetailTableData.data);
    // console.log('--index--',index);
    if (index + 1 > state.dictTableData.option.pageSize) {
      state.dictTableData.option.page =
        Math.floor((index + 1) / state.dictTableData.option.pageSize) + 1;

      let res = await request.get("/api/dict/query", {
        PageIndex: state.dictTableData.option.page,
        PageSize: state.dictTableData.option.pageSize,
        keyWords: state.query.name,
      });
      res.content = res.content.map((item) => {
        item.belong = state.dictDetailTableData.dictName;
        return item;
      });
      state.dictTableData.data = res.content;
      state.dictTableData.option.total = res.totalElements;

      description.value.tableRef.setCurrentRow(
        state.dictTableData.data[index - state.dictTableData.option.pageSize]
      );
      state.dictDetailTableData.id =
        state.dictTableData.data[
          index - state.dictTableData.option.pageSize
        ].id;
      state.dictDetailTableData.dictName =
        state.dictTableData.data[
          index - state.dictTableData.option.pageSize
        ].name;
    } else {
      description.value.tableRef.setCurrentRow(state.dictTableData.data[index]);
      state.dictDetailTableData.id = state.dictTableData.data[index].id;
      state.dictDetailTableData.dictName = state.dictTableData.data[index].name;
    }
    getDetail();
  }
});
</script>

<style lang="scss" scoped>
.el-row {
  height: 100%;
}

.el-col {
  height: 100%;
}
.app-title-box {
  height: 100%;
  box-sizing: border-box;
}
</style>
